<?php
namespace app\index\controller;

use app\common\model\User as UserModel;
use think\Controller;
use think\Loader;
require_once("../vendor/qqConnect/API/qqConnectAPI.php");
require_once '../vendor/gt/lib/class.geetestlib.php';
class Login extends Controller
{
    public function index()
    {
    	$this->assign('title',"登录");
        return $this->fetch();
    }

    public function weixinloin()
    {

    	$return_url = 'http://1o533n8683.imwork.net'.url('index/login/weixin_return');
    	
    	$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbac82045a637c02e&redirect_uri=".$return_url."&response_type=code&scope=snsapi_base&state=123#wechat_redirect";

    	// $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxbac82045a637c02e&redirect_uri=".$return_url."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";

    	$this->redirect($url);

    }

    public function weixin_return()
    {
    	$code = input('code');

    	$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxbac82045a637c02e&secret=7c320fea54e77a01fcc59ff7060b04e2&code=".$code."&grant_type=authorization_code";

    	$data = file_get_contents($url);

    	$data = json_decode($data,true);

    	$openid = $data['openid'];

    	$user = UserModel::get(['openid'=>$openid]);

		if($user){
			session('user',$user);
			$this->redirect(url(session('return_url')));
		}else{

			$url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$data['access_token']."&openid=".$openid."&lang=zh_CN";

			$user = file_get_contents($url);

    		$arr = json_decode($user,true);

			$data['nickname'] = $arr['nickname'];
			$data['openid'] = $openid;
			$data['sex'] = $arr['sex'];
			$data['city'] = $arr['city'];
			$data['face'] = $this->get_qq_face($arr['headimgurl']);

			$user = UserModel::create($data);

			if($user){
				session('user',$user);
				$this->redirect(url(session('return_url')));

			}else{
				session('user',$user);
				$this->error('qq登录用户创建失败',url('index/login/index'));
			}
		}
    }


    public function check_get()
    {
    	define("CAPTCHA_ID", "48a6ebac4ebc6642d68c217fca33eb4d");
		define("PRIVATE_KEY", "4f1c085290bec5afdc54df73535fc361");

		$GtSdk = new \GeetestLib(CAPTCHA_ID, PRIVATE_KEY);


		$data = array(
		        "user_id" => $_SESSION['user_id'], # 网站用户id
		        "client_type" => "web", #web:电脑上的浏览器；h5:手机上的浏览器，包括移动应用内完全内置的web_view；native：通过原生SDK植入APP应用的方式
		        "ip_address" => "127.0.0.1" # 请在此处传输用户请求验证时所携带的IP
		 );

		if ($_SESSION['gtserver'] == 1) {   //服务器正常
		    $result = $GtSdk->success_validate($_POST['geetest_challenge'], $_POST['geetest_validate'], $_POST['geetest_seccode'], $data);
		    if ($result) {
		        return true;
		    } else{
		        return false;
		    }
		}else{  //服务器宕机,走failback模式
		    if ($GtSdk->fail_validate($_POST['geetest_challenge'],$_POST['geetest_validate'],$_POST['geetest_seccode'])) {
		       return true;
		    }else{
		        return false;
		    }
		}
    }


    public function checkLogin()
    {
    	$data = input('post.');

    	if(!$this->check_get()){
    		$this->error('验证不通过');
    	}


  //   	$validate = Loader::validate('User');

		// if(!$validate->scene('login')->check($data)){

		// 	$this->error($validate->getError());
		// }

		if(strstr($data['loginName'],'@')){

			$user = UserModel::get([
				'email' =>$data['loginName'],
				'password'=>md5($data['password'])
			]);

		}else{
			$user = UserModel::get([
				'phone' =>$data['loginName'],
				'password'=>md5($data['password'])
			]);
		}

		if($user){
			if($user->status){
				$this->error('帐号异常，请联系管理解决！！！！');
			}
			session('user',$user);
			$this->success("登录成功");
		}else{
			$this->error('用户或者密码不正确');
		}
    }

    public function loginout()
    {
    	session('user',null);
    	$this->success("退出成功",url('index/login/index'));
    }

    public function qqlogin()
    {
    	
		$qc = new \QC();
		$qc->qq_login();
    }

    public function qqreturn()
    {
    	$qc = new \QC();

		$qc->qq_callback();

		$openid = $qc->get_openid();
		
		$user = UserModel::get(['openid'=>$openid]);

		if($user){
			session('user',$user);
			$this->redirect(url('index/user/index'));
		}else{

			$arr = $qc->get_user_info();

			$data['nickname'] = $arr['nickname'];
			$data['openid'] = $openid;
			$data['sex'] = $arr['gender'];
			$data['city'] = $arr['city'];
			$data['face'] = $this->get_qq_face($arr['figureurl_2']);

			$user = UserModel::create($data);

			if($user){
				session('user',$user);
				$this->redirect(url('index/user/index'));

			}else{
				session('user',$user);
				$this->error('qq登录用户创建失败',url('index/login/index'));
			}
		}
    }

    public function get_qq_face($url)
    {
    	// $url = "http://qzapp.qlogo.cn/qzapp/101545046/5596923EAFE81085C70D49A06D51C397/100";

    	$ch = curl_init();

    	curl_setopt($ch, CURLOPT_URL,$url);

    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    	$output = curl_exec($ch);


    	$dir = 'uploads/'.date("Ymd");

    	is_dir($dir) || mkdir($dir);

    	$filename = $dir."/".uniqid().'.png';

    	file_put_contents($filename ,$output);

    	return $filename;
    }

   
}

// http://1o533n8683.imwork.net/index/login/qqreturn
// 101545046
// 2ba415d5ef3f74fede98d55b55024244
